package com.gao.jwtdemo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gao.jwtdemo.domain.JwtPayload;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.MacSigner;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author GaoXi
 * @date 2021/5/14 20:22
 */
@RestController
public class TestController {

    //使用密码进行签名
    private final static String password ="123456";

    @Resource
    private ObjectMapper objectMapper;




    @GetMapping("jwt")
    public String getJwt() throws JsonProcessingException {
        MacSigner macSigner = new MacSigner(password);
        JwtPayload jwtPayload = new JwtPayload();
        jwtPayload.setAud("all");
        jwtPayload.setExp(LocalDateTime.now().plusDays(10));
        jwtPayload.setIss("gaoxi");
        jwtPayload.setUserId("1");
        String payload = objectMapper.writeValueAsString(jwtPayload);
        Jwt encode = JwtHelper.encode(payload, macSigner);
        System.out.println(encode.getClaims());
        return encode.getEncoded();
    }



    @GetMapping("verifyJwt")
    public String verifyJwt(String jwt) throws JsonProcessingException {
        MacSigner macSigner = new MacSigner(password);
        Jwt jwt1 = JwtHelper.decodeAndVerify(jwt, macSigner);
        String claims = jwt1.getClaims();
        JwtPayload jwtPayload = objectMapper.readValue(claims, JwtPayload.class);
        System.out.println(jwtPayload);
        return claims;
    }




}
